<template>
  <div class="home">
    <!-- 搜索框 -->
    <div class="search">
      <div class="wrapper">
        <img src="/static/imgs/search.png">
        <input placeholder-style='color: #fff'
               confirm-type='search' 
               placeholder='查询其他城市' 
               v-model="searchText"
               maxlength='20'
               @confirm='commitSearch'
        >
      </div>
    </div>

    <!-- 内容区 -->
    <div class="content" style="margin-top:120rpx">
      <div class="info">
        <!-- 城市 -->
        <div class="city">
          <p class="title">{{ cityDatas.city || '定位中' }}</p>
          <p class="time" v-if="cityDatas.updateTimeFormat">{{ cityDatas.updateTimeFormat }} 更新</p>
        </div>

        <!-- 温度 -->
        <div class="temp" v-if="cityDatas.temperature">
          <div>{{cityDatas.temperature}}</div><div style='font-size:90rpx'>°</div>
        </div>

        <!-- 天气  -->
        <div class="weather">
          {{ cityDatas.weather || '--'}}
        </div>

        <!-- pm -->
        <div class="pm" v-if="cityDatas.pmVal">
          <div>{{ cityDatas.pmDesc }} {{ cityDatas.pmVal }}</div>
        </div>
      </div>

      <div class="guide" v-if="cityDatas.weather_data">
        <div class="item" v-for="item in cityDatas.weather_data" :key="index">
          <div class="date i">{{ index===0?'今天':item.date }}</div>
          <div class="temperature i">{{ item.temperature }}</div>
          <div class="weather i">{{ item.weather }}</div>
          <div class="wind i">{{ item.wind }}</div>
        </div>
      </div>

      <div class="live" v-if="cityDatas.live">
        <div class="item" v-for="item in cityDatas.live" :key="index">
          <img :src="icons[index]" class="icon">
          <div class="right">
            <div class="key">{{item.tipt}} {{item.zs}}</div>
            <div class="value">{{item.des}}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 设置定位 -->
    <div class="openSettingButton" v-if="openSettingButtonShow">
      <image src='/static/imgs/unlock.png'></image>
      <button open-type='openSetting'></button>
    </div>

    <!-- 底部 -->
    <div class="from">
      数据来源 百度地图开放平台
    </div>

    <!-- 悬浮菜单 -->
    <div class="menus">
      <img src="/static/imgs/location.png"
           @click="menuOne" 
           :animation="animationOne" 
           
      >
      <!-- :style="{top: menuPos.top + 'px',left: menuPos.left + 'px'}" -->
      <img src="/static/imgs/setting.png"
           @click="menuTwo" 
           :animation="animationTwo" 
           
      >
      <img src="/static/imgs/info.png"
           @click="menuThree" 
           :animation="animationThree" 
           
      >
      <img src="/static/imgs/menu.png"
           @click="menuMain" 
           class="main" 
           :animation="animationMain" 
           @touchmove.stop='menuMainMove' 
           
      >
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import bmap from '@/utils/bmap-wx'
import { formatDate, cmpVersion } from '@/utils/utils'

export default {
  data () {
    return {
      searchText: '',
      cityDatas: {},
      loc: {},
      icons: [
        '/static/imgs/clothing.png',
        '/static/imgs/carwashing.png',
        '/static/imgs/pill.png',
        '/static/imgs/running.png',
        '/static/imgs/sun.png'
      ],
      openSettingButtonShow: false,
      hasPopup: false,
      animationMain: {},
      animationOne: {},
      animationTwo: {},
      animationThree: {},
      menuPos: {},
      cityChanged: false
    }
  },
  components: {},
  created () {},
  mounted () {
    this.init()
  },
  methods: {
    // 地理编码封装
    geocoder (address) {
      const that = this
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'http://api.map.baidu.com/geocoder/v2/',
          data: {
            address,
            output: 'json',
            ak: that.ak
          },
          success (res) {
            const data = res.data || {}
            if (!data.status) {
              const dataLocation = (data.result || {}).location || {}
              resolve(dataLocation)
            } else {
              wx.showToast({
                title: data.msg || '网络不给力，请稍后再试',
                icon: 'none'
              })
            }
          },
          fail (res) {
            wx.showToast({
              title: '网络不给力，请稍后再试',
              icon: 'none'
            })
          },
          complete () {
            that.searchText = ''
          }
        })
      })
    },

    // 获取天气数据
    init (location) {
      // 新建百度地图对象
      const BMap = new bmap.BMapWX({ ak: this.ak })
      // 发起weather请求
      BMap.weather({
        location: location ? `${location.lng},${location.lat}` : '',
        success: this.success,
        fail: this.fail
      })
    },

    // 搜索框提交
    commitSearch (e) {
      // 去空格
      const searchValue = ((e.target || {}).value || '').replace(/\s+/g, '')
      this.search(searchValue)
    },

    // 查询
    search(searchValue) {
      if (searchValue && searchValue !== '') {
        const loa = this.geocoder(searchValue)

        // 滚动到顶部
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        })
        loa.then(res => {
          this.loc = res
          this.init(res)
        })
      }
      this.searchText = ''
    },

    // 请求成功调用
    success (data) {
      // 授权按钮隐藏
      this.openSettingButtonShow = false

      wx.stopPullDownRefresh()

      const now = new Date()
      const temperature = data.originalData.results[0].weather_data[0].date.match(
        /\d+/g
      )[2]
      const pm = this.calcPM(data.originalData.results[0].pm25)

      // 当前时间
      data.updateTimeFormat = formatDate(now, 'MM-dd hh:mm')
      // 实时温度
      data.temperature = temperature
      // pm值
      data.pmVal = pm.val
      data.pmDesc = pm.desc
      // 二层数据
      data.oData = data.originalData.results[0]
      // 城市
      data.city = data.oData.currentCity
      // 天气
      data.weather = data.oData.weather_data[0].weather
      // 后续天气
      data.weather_data = data.oData.weather_data
      // 生活指数
      data.live = data.oData.index

      wx.setStorage({
        key: 'cityDatas',
        data: data
      })
      this.cityDatas = data
    },

    // 错误调用
    fail (res) {
      const that = this
      let errMsg = res.errMsg || ''

      wx.stopPullDownRefresh()
      if (errMsg.indexOf('deny') !== -1 || errMsg.indexOf('denied') !== -1) {
        wx.showToast({
          title: '需要开启地理位置权限',
          icon: 'none',
          duration: 2500,
          success (res) {
            if (that.canUseOpenSettingApi()) {
              let timer = setTimeout(() => {
                clearTimeout(timer)
                wx.openSetting({})
              }, 2500)
            } else {
              that.openSettingButtonShow = true
            }
          }
        })
      } else {
        wx.showToast({
          title: '网络不给力，请稍后再试',
          icon: 'none'
        })
      }
    },

    // pm值划分
    calcPM (value) {
      if (value > 0 && value <= 50) {
        return {
          val: value,
          desc: '优',
          detail: ''
        }
      } else if (value > 50 && value <= 100) {
        return {
          val: value,
          desc: '良',
          detail: ''
        }
      } else if (value > 100 && value <= 150) {
        return {
          val: value,
          desc: '轻度污染',
          detail: '对敏感人群不健康'
        }
      } else if (value > 150 && value <= 200) {
        return {
          val: value,
          desc: '中度污染',
          detail: '不健康'
        }
      } else if (value > 200 && value <= 300) {
        return {
          val: value,
          desc: '重度污染',
          detail: '非常不健康'
        }
      } else if (value > 300 && value <= 500) {
        return {
          val: value,
          desc: '严重污染',
          detail: '有毒物'
        }
      } else if (value > 500) {
        return {
          val: value,
          desc: '爆表',
          detail: '能出来的都是条汉子'
        }
      }
    },

    // 判断版本  button open-type openSetting 2.0.7 后支持
    canUseOpenSettingApi () {
      const SDKVersion = this.systemInfo.SDKVersion
      const version = cmpVersion(SDKVersion, '2.0.7')
      if (version < 0) {
        return true
      } else {
        return false
      }
    },

    // 获取城市缓存
    getCityStorage () {
      const that = this
      wx.getStorage({
        key: 'cityDatas',
        success: function (res) {
          that.cityDatas = res.data
        }
      })
    },

    // 菜单选项
    menuOne () {
      this.retract()
      wx.navigateTo({
        url: '../Citychoose/main'
      })
    },

    menuTwo () {
      this.retract()
      wx.navigateTo({
        url: '../Setting/main'
      })
    },

    menuThree () {},

    menuMain () {
      if (!this.hasPopup) {
        this.popup()
        this.hasPopup = true
      } else {
        this.retract()
        this.hasPopup = false
      }
    },

    // 菜单弹出动画
    popup () {
      let animationMain = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-out'
      })
      let animationOne = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-out'
      })
      let animationTwo = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-out'
      })
      let animationThree = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-out'
      })

      animationMain.rotateZ(180).step()
      animationOne
        .translate(-50, -60)
        .rotateZ(360)
        .opacity(1)
        .step()
      animationTwo
        .translate(-90, 0)
        .rotateZ(360)
        .opacity(1)
        .step()
      animationThree
        .translate(-50, 60)
        .rotateZ(360)
        .opacity(1)
        .step()

      this.animationMain = animationMain.export()
      this.animationOne = animationOne.export()
      this.animationTwo = animationTwo.export()
      this.animationThree = animationThree.export()
    },

    // 菜单缩回动画
    retract () {
      let animationMain = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-out'
      })
      let animationOne = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-out'
      })
      let animationTwo = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-out'
      })
      let animationThree = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-out'
      })

      animationMain.rotateZ(0).step()
      animationOne
        .translate(0, 0)
        .rotateZ(0)
        .opacity(0)
        .step()
      animationTwo
        .translate(0, 0)
        .rotateZ(0)
        .opacity(0)
        .step()
      animationThree
        .translate(0, 0)
        .rotateZ(0)
        .opacity(0)
        .step()

      this.animationMain = animationMain.export()
      this.animationOne = animationOne.export()
      this.animationTwo = animationTwo.export()
      this.animationThree = animationThree.export()
    },

    // 菜单移动
    menuMainMove (e) {
      const windowWidth = this.systemInfo.windowWidth
      const windowHeight = this.systemInfo.windowHeight
      let clientX = e.clientX
      let clientY = e.clientY

      // 先收回
      if (this.hasPopup) {
        this.retract()
        this.hasPopup = false
      }
      // 边界判断
      if (clientX > windowWidth - 40) {
        clientX = windowWidth - 40
      }
      if (clientX <= 90) {
        clientX = 90
      }
      if (clientY > windowHeight - 40 - 60) {
        clientY = windowHeight - 40 - 60
      }
      if (clientY <= 60) {
        clientY = 60
      }
      this.menuPos = {
        left: clientX,
        top: clientY
      }
    }
  },
  onShow () {
    const page = getCurrentPages();
    const currentP = page[page.length - 1];

    this.cityChanged = currentP.data.cityChanged
    this.searchText = currentP.data.searchText
    
    // this.getCityStorage()
    if(!this.cityChanged) {
      this.init()
    }
    else {      
      this.search(this.searchText)
      this.searchText = ''
      this.cityChanged = false
    }
  },
  // 下拉刷新
  onPullDownRefresh () {
    if (this.loc.lng) this.init(this.loc)
    else this.init()
  },
  // 分享
  onShareAppMessage (res) {
    return {
      title: 'Weather--天气',
      path: '/pages/Home/main',
      success () {},
      fail (e) {
        let errMsg = e.errMsg || ''
        // 对不是用户取消转发导致的失败进行提示
        let msg = '分享失败，可重新分享'
        if (errMsg.indexOf('cancel') !== -1) {
          msg = '取消分享'
        }
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.home {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  color: #fff;
  font-size: 30rpx;

  .search {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 90rpx;
    .wrapper {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      box-sizing: border-box;
      font-size: 28rpx;
      height: 60rpx;
      margin: 15rpx 50rpx;
      padding: 0 15rpx;
      border-bottom: 1rpx solid #fff;
      img {
        width: 28rpx;
        height: 28rpx;
        margin-right: 16rpx;
      }
    }
  }
  .content {
    flex: 2;
    .city,
    .info .temp,
    .info .weather {
      position: relative;
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
    }
    .info {
      text-align: center;
      padding-bottom: 50rpx;
      .city {
        position: relative;
        height: 90rpx;
        font-size: 36rpx;
        .title {
          display: inline-block;
          line-height: 90rpx;
        }
        .time {
          position: absolute;
          right: 30rpx;
          top: 50%;
          transform: translateY(-50%);
          font-size: 24rpx;
        }
      }
      .temp {
        width: 100%;
        height: 360rpx;
        font-size: 200rpx;
      }
      .weather {
        margin-bottom: 30rpx;
        font-size: 30rpx;
      }
      .pm {
        display: inline-block;
        div {
          font-size: 24rpx;
          height: 1em;
          line-height: 1em;
          padding: 10rpx 20rpx;
          border-radius: 20rpx;
          background: rgba(240, 240, 240, 0.2);
        }
      }
    }
    .guide {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      font-size: 24rpx;
      padding-top: 20rpx;
      background: rgba(6, 85, 114, 0.1);
      margin-bottom: 20rpx;
      .item {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: center;
      }
      .i {
        padding-bottom: 20rpx;
      }
    }
    .live {
      /* border-bottom: 1rpx solid rgba(240, 240, 240, .4); */
      background: rgba(6, 85, 114, 0.1);
      margin-bottom: 20rpx;
      .item {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        border-bottom: 1rpx solid rgba(250, 250, 250, 0.2);
        padding: 20rpx 0;
        margin: 0 30rpx;
        &:last-child {
          border-bottom: none;
        }
        .icon {
          width: 80rpx;
          height: 80rpx;
          padding: 0 24rpx;
        }
        .right {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: flex-start;
          flex: 1;
          .value {
            margin-top: 10rpx;
            font-size: 24rpx;
          }
        }
      }
    }
  }
  .openSettingButton {
    position: fixed;
    z-index: 102;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    image {
      position: relative;
      width: 128rpx;
      height: 128rpx;
      z-index: 2;
    }
    button {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      opacity: 0;
      z-index: 3;
    }
  }
  .from {
    position: relative;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    padding: 10rpx 0;
    height: 70rpx;
    font-size: 22rpx;
  }
  .menus {
    img {
      height: 40px;
      width: 40px;
      position: fixed;
      z-index: 100;
      bottom: 150rpx;
      right: 70rpx;
      opacity: 0;
      &.main {
        opacity: 1;
      }
    }
  }
}
</style>
